<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>组件基础</title>
        <style>
            v-cloak { display: none; }
            .wrapper { border: 1px solid blue ; }
            .counter { border: 1px solid gray; margin: 10px; user-select: none; }
        </style>
    </head>
    <div>

        <div id="first" v-cloak></div>

        <script src="vue@3.2.45.js" type="text/javascript"></script>

        <script>

            // 定义计数器组件(实际上是定义了计数器组件的相关选项)
            const CounterComponent = {
                template: `<div @click="evt => count < max ? count++ : count" class="counter">
                                你已经点击了{{name}}{{count}}次
                           </div>`,
                // 这里的 name 与 父组件中 `<counter name="老大" max="10"></counter>` 的 name 对应
                props: [ 'name', 'max' ],
                data() {
                    return { count: 1 }
                },
                // 实例初始化完成且 props 解析后、data() 和 computed 等选项处理之前立即调用
                beforeCreate() {
                    console.log( 'beforeCreate - name:', this.name );
                    console.log( `beforeCreate - Object.hasOwn(this, 'count'):`, Object.hasOwn(this, 'count') );
                },
                // 在组件实例处理完所有与状态相关的选项后调用
                created() {
                    console.log( 'created - name:', this.name );
                    console.log( `created - Object.hasOwn(this, 'count'):`, Object.hasOwn(this, 'count') );
                    console.log( 'created - count:', this.count );
                },
                updated() {
                    console.log( 'updated - name:', this.name );
                }
            }

            // 定义根组件(实际上是定义了根组件的相关选项)
            const RootComponent = {
                // 注册子组件(局部注册)
                components: {
                    counter: CounterComponent
                },
                template: `<div class="wrapper">
                              <counter name="老大" max="10"></counter>
                              <counter v-bind:name="second" max="50"></counter>
                              <counter :name="third" :max="thirdMax"></counter>
                              <button @click="change">更改数据属性</button>
                           </div>`,
                data() {
                    return {
                        first: '老大',
                        second: '老二',
                        third: '小三',
                        thirdMax: 2000
                    }
                },
                methods: {
                    change() {
                        this.first = '老一'
                        this.second = '小二';
                        this.third = '老幺';
                    }
                }
            }
            // 创建应用实例 (在应用中已经挂载了一个根组件)
            const app = Vue.createApp(RootComponent);
            // 挂载应用到DOM节点
            app.mount( '#first' );
        </script>
    </div>
</html>